package top.csy8888.placeorder.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.csy8888.placeorder.common.config.RabbitConfig;
import top.csy8888.placeorder.entity.Order;
import top.csy8888.placeorder.mapper.GoodsMapper;
import top.csy8888.placeorder.mapper.OrderMapper;

/**
 * @author CSY
 * @date 2025 - 10 - 16
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderConsumerService {
    private final OrderMapper orderMapper;

    private final GoodsMapper goodsMapper;

    private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 如果用户在指定的时间内没有完成支付则修改订单状态为失效，并且要回填库存
     *
     * 如果完成支付则修改订单状态为已支付，并且扣减数据库库存
     * @param orderId
     */
    @RabbitListener(queues = RabbitConfig.DELAY_QUEUE)
    public void receive(Integer orderId){
        Order order = orderMapper.getOrderById(orderId);
        //如果处于未支付的状态
        if (order.getOrderStatus() == 0){
            //修改订单为失效状态
            order.setOrderStatus(2);
            orderMapper.update(order);
            //回填缓存的库存
            redisTemplate.opsForValue().increment(GoodsEnum.STOCK_PREFIX.value() + order.getGid());
        }else if (order.getOrderStatus() == 1){
            //如果订单为已支付状态，扣减数据库库存
            goodsMapper.decrStock(order.getGid());
        }
    }
}
